package com.xeware.chatter.model;

import java.util.Iterator;

import com.sforce.soap.partner.sobject.SObject;
import com.sforce.ws.bind.XmlObject;

public final class DFeedTrackedChanges {
	public String OldValue = "";
	public String NewValue = "";
	public String Id = "";
	public String FieldName = "";
	public boolean valid = false;

	public DFeedTrackedChanges(SObject s) { 
		Iterator <XmlObject> skids = s.getChildren();
		while (skids.hasNext()) {
			XmlObject tcxo = skids.next();
			String tcName = tcxo.getName().getLocalPart().toString();
			//System.out.println(tcName);
			if(tcName.equals("FeedTrackedChanges")) {
				this.valid = this.processIterator(tcxo.getChildren());
				continue;						
			}
		}
	}

	public boolean processIterator(Iterator <XmlObject> ftci) {
		while (ftci.hasNext()) {
			XmlObject xokid = ftci.next();
			String xokName = xokid.getName().getLocalPart().toString();
			if (xokName.equals("records")) {
				Iterator <XmlObject> rkids = xokid.getChildren();
				while(rkids.hasNext()) {
					XmlObject rkid = rkids.next();
					String rkName = rkid.getName().getLocalPart().toString();
					try {
						if (rkName.equals("FieldName")) {
							this.FieldName = rkid.getValue().toString();
						} else if(rkName.equals("OldValue")) {
							this.OldValue = rkid.getValue().toString();
						} else if(rkName.equals("NewValue")) {
							this.NewValue = rkid.getValue().toString();
						}
						//System.out.println(rkName+": "+rkid.getValue().toString());
					} catch (NullPointerException e) {

					} 
				}
				continue;
			}

		}
		if (this.FieldName.length() > 0) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	public String toString() {
		String mstring = "";
		if (this.FieldName.equals("User.AboutMe")) {
			mstring = "updated their profile.";
		} else if(this.FieldName.equals("CollaborationGroup.Name")) {
			mstring = "changed group name from "+this.OldValue+" to "+ this.NewValue + ".";
		} else if(this.FieldName.equals("created")) {
			mstring = "created this group.";
		} else if(this.FieldName.equals("CollaborationGroup.Description")) {
			mstring = "changed group description.";
		} else {
			mstring = "changed: " + this.FieldName;
		}
		return mstring;
	}
}
